package com.corn.security;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.corn.entity.SysUser;
import com.corn.mapper.SysUserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @author : Jim Wu
 * @version 1.0
 * @function :
 * @since : 2021/4/8 14:55
 */

@RequiredArgsConstructor
@Service
public class MyUserDetailService implements UserDetailsService {
    private final SysUserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUsername, username);
        SysUser sysUser = userMapper.selectOne(wrapper);
        if (null == sysUser)
            throw new UsernameNotFoundException("用户不存在");
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return new User(sysUser.getUsername(), passwordEncoder.encode(sysUser.getPassword()), AuthorityUtils.createAuthorityList("add", "delete", "select"));
    }
}
